
/**
 * nobittercipher.cpp
 * 
 * NobitterCipher is a cipher to code a plain text to a tinyurl
 * 
 * Copyright (c) 2008 Harunobu Oyama <nobukichi at gmail.com>
 * Licensed under GNU GPL version 3
 *
 */

#ifdef WIN32
#pragma warning( disable:4786 )
#endif

#include	"textcipher.h"
#include	"tinyurlapi.h"
#include	"nobittercipher.h"


NobitterCipher::NobitterCipher(const QString& url, const QString& key, QObject* parent)
  : QObject(parent), baseUrl(url), encryptionKey(key)
{
	pTinyUrlAPI = new TinyUrlAPI(this);

	connect( pTinyUrlAPI, SIGNAL(signalDetectedHttpError(QHttp::Error)), 
	         this, SLOT(slotReportHttpError(QHttp::Error)) );
	connect( pTinyUrlAPI, SIGNAL(signalEncodeFinished(const QString&, const QString&)), 
	         this, SLOT(slotReportEncryptedUrl(const QString&, const QString&)) );
	connect( pTinyUrlAPI, SIGNAL(signalDecodeFinished(const QString&, const QString&)), 
	         this, SLOT(slotReportDecryptedText(const QString&, const QString&)) );
}

void NobitterCipher::reset()
{
	pTinyUrlAPI->reset();
}
	
void NobitterCipher::setKey(const QString& key)
{
	encryptionKey = key;
}

void NobitterCipher::encrypt(const QString& text)
{
	QString encryptedBase64Text = TextCipher::encode(text, encryptionKey);
	QString orgUrl = baseUrl + encryptedBase64Text;
	originalUrlToPlainTextCache[orgUrl] = text;
	pTinyUrlAPI->requestEncode(orgUrl);
}

void NobitterCipher::decrypt(const QString& encryptedUrl)
{
	pTinyUrlAPI->requestDecode(encryptedUrl);
}

void NobitterCipher::slotReportHttpError(QHttp::Error error)
{
	emit signalDetectedHttpError(error);
}

void NobitterCipher::slotReportEncryptedUrl(const QString& orgUrl, const QString& tinyUrl)
{
	QString text = originalUrlToPlainTextCache[orgUrl];
	emit signalEncrypted(text, tinyUrl);
	originalUrlToPlainTextCache.erase(orgUrl);
}

void NobitterCipher::slotReportDecryptedText(const QString& tinyUrl, const QString& orgUrl)
{
	if (orgUrl.startsWith(baseUrl)) {
		QString encryptedBase64Text = orgUrl.mid(baseUrl.size());
		QString plainText = TextCipher::decode(encryptedBase64Text, encryptionKey);
		emit signalDecrypted(tinyUrl, plainText);
	} else {
		//! the tiny url is not encrypted with NobitterCipher.
		emit signalDecrypted(tinyUrl, tinyUrl);
	}
}

